package cn.dapeng.features;


/**
 * 这个例子演示了 synchronized 关键字的作用：具有可见性  所以index变量前没有加volatile关键字
 * <p>
 * volatile 和 synchronized 都具有可见性
 * 但是 volatile 不保证原子性
 */
public class Sync_T01 {
    private static int index = 0;

    public synchronized static void m1() {
        index++;
    }

    public static void main(String[] args) throws Exception {

        int threadCount = 100;
        Thread[] threads = new Thread[threadCount];

        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    m1();
                }
            });
            threads[i].start();
        }

        for (int i = 0; i < threadCount; i++) {
            threads[i].join();
        }

        System.out.println("sum ::: " + index);

    }
}
